package top.broncho.lottery.util

import android.content.Context
import android.net.ConnectivityManager
import android.view.View

/***
 * 带延迟过滤的点击事件View扩展
 * @param delay Long 延迟时间，默认600毫秒
 * @param block: (T) -> Unit 函数
 * @return Unit
 */
fun <T : View> T.clickWithTrigger(delay: Long = 800L, block: (T) -> Unit) {
    setOnClickListener {
        if (clickEnable(delay)) {
            block(it as T)
        }
    }
}

private var <T : View> T.triggerLastTime: Long
    set(value) = setTag(1766613352, value)
    get() = getTag(1766613352) as? Long ?: 0

private fun <T : View> T.clickEnable(delay: Long): Boolean {
    var flag = false
    val currentClickTime = System.currentTimeMillis()
    if (currentClickTime - triggerLastTime > delay) {
        flag = true
    }
    triggerLastTime = currentClickTime
    return flag
}

fun Context.isWifiOpen(): Boolean {
    val cm =
        getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
    val info = cm.activeNetworkInfo
    return info != null && info.isAvailable && info.isConnected
            && info.type == ConnectivityManager.TYPE_WIFI
}

fun Context.hasInternet(): Boolean {
    val cm =
        getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
    val info = cm.activeNetworkInfo
    return info != null && info.isAvailable && info.isConnected
}

